// pages/gps/gps.js

const app = getApp()
var util = require("../../utils/util.js")
app._polyline = []
//------------------------------
//World Geodetic System ==> Mars Geodetic System
//translate from https://on4wp7.codeplex.com/SourceControl/changeset/view/21483#353936
var WGS84_to_GCJ02 = function () { }

WGS84_to_GCJ02.prototype.a = 6378245.0;
WGS84_to_GCJ02.prototype.ee = 0.00669342162296594323;
WGS84_to_GCJ02.prototype.transform = function (wgLat, wgLon) {

  if (this.outOfChina(wgLat, wgLon)) {
    return [wgLat, wgLon];
  }

  var dLat = this.transformLat(wgLon - 105.0, wgLat - 35.0);
  var dLon = this.transformLon(wgLon - 105.0, wgLat - 35.0);
  var radLat = wgLat / 180.0 * Math.PI;
  var magic = Math.sin(radLat);
  var magic = 1 - this.ee * magic * magic;
  var sqrtMagic = Math.sqrt(magic);
  var dLat = (dLat * 180.0) / ((this.a * (1 - this.ee)) / (magic * sqrtMagic) * Math.PI);
  var dLon = (dLon * 180.0) / (this.a / sqrtMagic * Math.cos(radLat) * Math.PI);
  var mgLat = wgLat + dLat;
  var mgLon = wgLon + dLon;

  return [mgLat, mgLon];

};

WGS84_to_GCJ02.prototype.outOfChina = function (lat, lon) {

  if (lon < 72.004 || lon > 137.8347)
    return true;
  if (lat < 0.8293 || lat > 55.8271)
    return true;

  return false;

};

WGS84_to_GCJ02.prototype.transformLat = function (x, y) {

  var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
  ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
  ret += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;

  return ret;

};

WGS84_to_GCJ02.prototype.transformLon = function (x, y) {

  var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
  ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
  ret += (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
  ret += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0;

  return ret;

};
//------------------------------

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imei: "862285033462874",
    gps_dev: {},
    gps_loc: {
      lng: 113.324520,
      lat: 23.099994
    },
    gps_sta: {},
    gcj02: {
      lng: 113.324520,
      lat: 23.099994
    },
    mode_realtime_color: "#00FF00FF",
    mode_history_color: "#FF0000FF",
    vmode: "realtime"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    var last_imei = wx.getStorageSync('last_imei') || ""
    if (last_imei) {
      that.setData({ imei: last_imei })
    }
    else {
      last_imei = "862285033462874"
      that.setData({ imei: last_imei })
      wx.setStorageSync("last_imei", last_imei)
    }
    setTimeout(function () {
      that.update_imei(last_imei)
      that.setup_ws()
    }, 1000)
  },
  setup_ws: function () {
    var that = this;
    // -------------
    console.log("open websocket for data update")
    wx.connectSocket({
      url: "wss://gps.nutz.cn/websocket",
    })
    //连接成功
    wx.onSocketOpen(function () {
      console.log("websocket connected, send join")
      wx.sendSocketMessage({
        data: JSON.stringify({ action: 'join', room: that.data.imei })
      })
      //wx.showToast({
      //  title : "已连接服务器"
      //})
    })
    wx.onSocketMessage(function (data) {
      var re = JSON.parse(data.data);
      if (re && re.loc) {
        console.log("loc update", that.data.vmode)
        that.setData({
          gps_loc: re.loc
        })
        if (that.data.vmode == "realtime")
          that.update_map_view()
      }
      else if (re && re.sta) {
        console.log("sta update", that.data.vmode)
        that.setData({
          gps_sta: re.sta
        })
        if (that.data.vmode == "realtime")
          that.update_map_view()
      }
    })
    wx.onSocketClose(function () {
      console.log("ws reconnecting ...")
      setTimeout(that.setup_ws, 1000)
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  update_imei: function (imei) {
    var that = this
    wx.request({
      url: 'https://gps.nutz.cn/gps/dev/info/' + imei,
      data: {
        session_id: "none"
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        if (res.statusCode == 200) {
          if (res.data && res.data.ok) {
            var dev = res.data.data
            var loc = res.data.data.loc
            res.data.data.loc = null
            console.log(dev, loc)
            that.setData({ imei: imei, gps_dev: dev, gps_loc: loc})
            wx.setStorageSync("last_imei", imei)
            wx.closeSocket({})
            that.update_map_view()
          }
          else if (res.data && res.data.msg) {
            if (res.data.msg == "no_such_dev")
              wx.showToast({ title: "设备不存在:" + imei })
            else
              wx.showToast({ title: "未知错误:" + res.data.msg + ":" + imei })
          }
          else {
            wx.showToast({ title: "未知错误:" + res.data + ":" + imei })
          }
        }
        else {
          wx.showToast({ title: "服务器异常:" + res.statusCode })
        }
      },
      fail(res) {
        wx.showToast({ title: "未知异常:" + res })
      }
    })
  },
  change_imei: function () {
    var that = this
    console.log("wx.scanCode")
    wx.scanCode({
      success: (res) => {
        if (res.result) {
          console.log("scan result: " + res.result)
          var imei = res.result.trim()
          if (/^[0-9]{15,16}$/.test(imei)) {
            that.update_imei(imei)
            return
          }
          else {
            wx.showToast({
              title: '不是合法的imei值:' + res.result,
            })
          }
        }
      }
    })
  },
  update_map_view: function () {
    var that = this;
    var loc = that.data.gps_loc
    if (that.data.vmode == "history") {
      if (app._polyline) {
        var _polyline = app._polyline
        console.log("loading tracking", _polyline[0].points.length)
        that.setData({
          gcj02: {
            lat: _polyline[0].points[0].latitude,
            lng: _polyline[0].points[0].longitude
          },
          markers: [],
          polyline: _polyline
        })
      }
      else {
        console.log("loading tracking", 0)
        that.setData({
          markers: [],
          polyline: []
        })
      }
    }
    else if (loc && loc.lng) {
      //console.log(loc)
      //console.log(new Date(loc.devtime*1000))
      var devtime = util.formatTime(new Date(loc.devtime * 1000))
      //console.log(devtime)
      var lat = loc.lat
      var lng = loc.lng
      var gcj02_loc = new WGS84_to_GCJ02().transform(lat, lng)
      var msg = loc.fixed ? "GPS定位" : "基站定位"
      msg += "\n" + gcj02_loc[0].toFixed(7) + "\n" + gcj02_loc[1].toFixed(7)
      msg += "\n卫星数" + loc.sateCnt
      if (that.data.gps_sta && that.data.gps_sta.csq) {
        msg += "\nGSM信号强度" + that.data.gps_sta.csq
      }
      msg = devtime + "\n" + msg
      that.setData({
        gcj02: {
          lat: gcj02_loc[0],
          lng: gcj02_loc[1]
        },
        markers: [{
          id: 1,
          latitude: gcj02_loc[0],
          longitude: gcj02_loc[1],
          label: {
            content: msg,
            color: "#FF0000DD"
          }
        }],
        polyline: []
      })
    }
  },
  show_points: function () {
    var that = this
    wx.showToast({
      title: '正在加载轨迹',
    })
    wx.request({
      url: 'https://gps.nutz.cn/gps/dev/locs/' + that.data.imei + "?mpmap=true",
      success: function (res) {
        if (res.statusCode == 200) {
          wx.hideToast()
          //console.info("loading tracking datas", res.data.length)
          //console.log("轨迹数据", res.data)
          app._polyline = [{
            points: res.data,
            color: "#0000FFFF",
            width: 2,
            arrowLine: true
          }]
        }
        else {
          app._polyline = []
          wx.showToast({
            title: '最近一天无轨迹',
          })
        }
        setTimeout(that.update_map_view, 500)
      }
    })
  },
  mode_realtime: function () {
    this.setData({
      vmode: "realtime",
      mode_realtime_color: "#00FF00FF",
      mode_history_color: "#FF0000FF",
    })
    this.update_map_view()
  },
  mode_history: function () {
    this.setData({
      vmode: "history",
      mode_realtime_color: "#FF0000FF",
      mode_history_color: "#00FF00FF",
    })
    this.show_points()
  },
})